package org.biubiu0002.baiblog.im.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.biubiu0002.baiblog.im.concurrent.FutureTaskScheduler;
import org.biubiu0002.baiblog.im.constants.MessageConstants;
import org.biubiu0002.baiblog.im.dto.message.Message;
import org.biubiu0002.baiblog.im.processor.ChatProcessor;
import org.biubiu0002.baiblog.im.session.ServerSession;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: biubiu0002
 * @Date: 2022/9/2 15:36
 **/
@Component
@ChannelHandler.Sharable
@Slf4j
public class MessageRedirectHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private ChatProcessor chatProcessor;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(!(msg instanceof Message)){
            super.channelRead(ctx,msg);
            return;
        }
        ServerSession session = ServerSession.getSession(ctx);
        if(session==null||!session.isLogin()){
            log.error("用户未登录，不能发送消息");
            return;
        }
        Message message = (Message) msg;
        Integer type = message.getType();
        switch (type){
            case MessageConstants.MessageType.REQUEST:{
                FutureTaskScheduler.add(()->{
                    chatProcessor.action(session,message);
                });
                break;
            }

            case MessageConstants.MessageType.RESPONSE:{
                break;
            }

            case MessageConstants.MessageType.NOTIFICATION:{
                break;
            }
            default:{

            }

        }
        if(type!=MessageConstants.MessageType.REQUEST){
            super.channelRead(ctx,msg);
        }





    }
}
